using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Win32.SafeHandles;

namespace PipeCSharp
{
    [StructLayout(LayoutKind.Sequential)]
    public class SecurityAttributes
    {
        public int nLength;
        public unsafe byte* pSecurityDescriptor = null;
        public int bInheritHandle;
    }

    public class Win32Native
    {
        public static int NMPWAIT_USE_DEFAULT_WAIT = 0x00000000;
        public static int GENERIC_WRITE = 0x40000000;
        public static int OPEN_EXISTING = 3;
        public static int FILE_ATTRIBUTE_NORMAL = 0x00000080;


        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, SecurityAttributes securityAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);


        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern unsafe int ReadFile(SafeFileHandle handle, byte* bytes, int numBytesToRead, out int numBytesRead, IntPtr mustBeZero);



        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern unsafe int WriteFile(SafeFileHandle handle, byte* bytes, int numBytesToWrite, IntPtr numBytesWrittenMustBeZero, NativeOverlapped* lpOverlapped);



        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern unsafe int WriteFile(SafeFileHandle handle, byte* bytes, int numBytesToWrite, out int numBytesWritten, IntPtr mustBeZero);


        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern int WaitNamedPipe(string lpNamedPipeName, int nTimeOut);


        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern int CloseHandle(IntPtr hObject);

        public static SecurityAttributes GetSecAttrs(FileShare share)
        {
            SecurityAttributes structure = null;
            if ((share & FileShare.Inheritable) != FileShare.None)
            {
                structure = new SecurityAttributes();
                structure.nLength = Marshal.SizeOf(structure);
                structure.bInheritHandle = 1;
            }
            return structure;
        }





    }
}